<template>
  <div class="login-page flex items-center justify-center">
    <div class="login-form">
      <ElForm :model="form" label-width="auto">
        <ElFormItem label="手机号">
          <ElInput v-model="form.phone" />
        </ElFormItem>
        <ElFormItem label="密码">
          <ElInput v-model="form.usrpassword" type="password" :show-password="true" />
        </ElFormItem>
        <div class="flex justify-center mt-4">
          <el-button @click="handleSubmit">登录</el-button>
        </div>
      </ElForm>
    </div>
  </div>
</template>

<script setup lang="ts">
import { loginService } from '@/api/login';

import { ElForm, ElFormItem, ElInput, ElButton } from 'element-plus';
import { reactive } from 'vue';
import { useUserStore, useToken } from '@/store/user';

const { setUser } = useUserStore();
const { setToken } = useToken();
const form = reactive({
  phone: '',
  usrpassword: '',
});

const handleSubmit = () => {
  console.log(form);
  const params = {
    username: form.phone,
    password: form.usrpassword,
  };
  let fullPhone = form.phone;
  if (form.phone.length == 11 && form.phone.substring(0, 1) === '1') {
    fullPhone = `0086${form.phone}`;
  } else {
    if (form.phone.startsWith('+')) {
      fullPhone = `00${form.phone.substring(1)}`;
    } else if (!form.phone.startsWith('00')) {
      fullPhone = `00${form.phone}`;
    }
  }
  params.username = fullPhone;
  loginService(params).then((data) => {
    console.log(data);
    if (data) {
      const loginInfo = {
        uid: data.uid,
        appID: data.appID,
        shortNo: data.shortNo,
        name: data.name,
        sex: data.name,
      };
      setUser(loginInfo);
      if (data.token) {
        setToken(data.token);
      }
    }
  });
};
</script>

<style lang="scss">
.login-page {
  height: 100vh;
  background-color: #f5f5f5;

  .logon-form {
    border-radius: 6px;
    background-color: rgba(255, 255, 255, 0.8);
    box-shadow: 0 0 5px 5px rgba(30, 30, 50, 0.2);
    padding: 20px;
    width: 300px;
  }
}
</style>
